package com.jbm.enterapplication.userlogin.presenter

import android.content.Context
import android.content.Intent
import android.view.View
import com.jbm.core.common.MainServer
import com.jbm.enterapplication.InterfaceMa
import com.jbm.enterapplication.activityhome.view.OpenDoor
import com.jbm.enterapplication.sharedprefer.SharedPreActivity
import com.jbm.enterapplication.userlogin.mode.User_mode_Login
import com.jbm.enterapplication.userlogin.view.User_View_Login_In
import com.jbm.enterapplication.utlisclass.Constant.*
import com.jbm.enterapplication.utlisclass.HttpNet
import com.jbm.enterapplication.view.DialogLoading
import com.jbm.enterapplication.view.DoubleButtonDialog
import com.jbm.jbmsupplier.activity.register.view.Register_Construction_WX
import com.jbm.onehome.common.OHInterface
import com.jbm.onehome.iface.Login
import com.zhy.http.okhttp.OkHttpUtils
import com.zhy.http.okhttp.callback.StringCallback
import org.json.JSONObject
import org.json.alipay.JSONException
import rx.Observable
import rx.Observer


/**
 * Created by 家帮忙 on 2017/9/4.
 */
class User_Present_Login : User_Present_Login_In {
    override fun getWXLogin() {//微信登录
        if (!WX_CODE.equals("")){
        LoadWEIXINInfo()}
    }


    private var userviewlogin: User_View_Login_In? = null
    private var context: Context? = null
    private var usermodelogin: User_mode_Login? = null
    var sharedPreferActivity: SharedPreActivity? = null

    constructor(userviewlogin: User_View_Login_In?, context: Context?) {
        this.userviewlogin = userviewlogin
        this.context = context
        usermodelogin = User_mode_Login()
        sharedPreferActivity = SharedPreActivity(context)

    }

     var  dialogLoading: DialogLoading?=null

    override fun getUserLogin() {
        if (userviewlogin?.getUserName().equals("")) {
            userviewlogin?.getUserNameerr()?.error = "请检查手机号是否为空"
            return

        } else if (userviewlogin?.getUserName()?.length!! < 11) {
            userviewlogin?.getUserNameerr()?.error = "请确认手机号"
            return
        } else if (userviewlogin?.getUserPwd().equals("请检查密码是否为空")) {
            userviewlogin?.getUserPwderr()?.error = ""
            return
        } else {
            dialogLoading = DialogLoading(context!!, "登录中.....", true)
            dialogLoading?.show()
            usermodelogin?.getUserLogin(userviewlogin?.getUserName()!!, userviewlogin?.getUserPwd()!!, object : InterfaceMa<String> {
                override fun onSuccess(t: String, boolean: Boolean) {
                    if (t.equals("1")) {
                        setDialogding()
                        sharedPreferActivity?.setIsUser(userviewlogin?.getUserName()!!, userviewlogin?.getUserPwd()!!)
                        sharedPreferActivity?.setIsLogin(boolean)//判断是否登陆
                        sharedPreferActivity?.setIsConn(boolean)//判断是否第一次连接服务器，如果登录成功就设为true 代表第一次链接成功
                        sharedPreferActivity?.setLoginId(OHInterface.getG_server().login_id.toString())
                        MainServer.getG_server().m_local_id = OHInterface.getG_server().login_id
                        context?.startActivity(Intent(context, OpenDoor::class.java))
                        userviewlogin?.finishs()
                    }
                }
                override fun setError(err: String, boolean: Boolean) {
                    /**
                     * err
                     * 2请求网络超时
                     * 3请求超时
                     * 4没有网络
                     * 5任意错误
                     */
                    if (err.equals("2")) {
                        setDialogding()
                        hint("请求网络超时")
                    } else if (err.equals("3")) {
                        setDialogding()
                        hint("请求超时")
                    } else if (err.equals("4")) {
                        setDialogding()
                        hint("未连接网络，请联网后在进入")
                    } else {
                        setDialogding()
                        hint(err)
                    }

                }

            })

        }


    }

    //一些提示的时候调用
    fun hint(name: String) {
        val dialog = DoubleButtonDialog(context, name)
        dialog.getokbtn().setOnClickListener(View.OnClickListener { dialog.dismiss() })
        dialog.setisVisibility()

    }

    fun setDialogding() {
        if (dialogLoading != null) {
            dialogLoading!!.dismiss()
        }
    }

    private fun LoadWEIXINInfo() {
        Thread(Runnable {
            val accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$WX_APP_ID&secret=$WX_SECRET&code=$WX_CODE&grant_type=authorization_code"
            OkHttpUtils.get().url(accessTokenUrl).build().execute(object : StringCallback() {
                override fun onError(call: okhttp3.Call?, e: java.lang.Exception?) {
                }
                override fun onResponse(response: String?) {
                    if (response != null) {
                        try {
                            val json = JSONObject(response)
                            val accessToken = json.getString("access_token")
                            var openId = json.getString("openid")
                            if (accessToken != null) {
                                val userUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken + "&openid=" + openId
                                OkHttpUtils.get().url(userUrl).build().execute(object : StringCallback() {
                                    override fun onError(call: okhttp3.Call?, e: java.lang.Exception?) {
                                    }

                                    override fun onResponse(response: String) {
                                        var json: JSONObject? = null
                                        try {
                                            json = JSONObject(response)
                                            val userName = json.getString("unionid")//id
                                            val nickname = json.getString("nickname")//昵称
                                            val headumgur = json.getString("headimgurl")//图片
                                            val sex = json.getInt("sex")
                                            sharedPreferActivity?.setIsUser(userName,"")
                                            sharedPreferActivity?.setLoginId(userName)
                                            sharedPreferActivity?.setWXname(nickname)
                                            sharedPreferActivity?.setWXhand(headumgur)
                                            sharedPreferActivity?.setWXsex(sex.toString())
                                            usermodelogin?.getWXLogin(userName,"",openId,object :InterfaceMa<String>{
                                                override fun onSuccess(t: String, boolean: Boolean) {
                                                    /**
                                                     * 1代表登录成功了
                                                     * 2代表没有成功 用户还没注册
                                                     */
                                                    if(boolean==true){
                                                    if (t.equals("1")){
                                                        sharedPreferActivity?.setIsUser(userName, "")
                                                        sharedPreferActivity?.setIsLogin(boolean)//判断是否登陆
                                                        sharedPreferActivity?.setIsConn(boolean)//判断是否第一次连接服务器，如果登录成功就设为true 代表第一次链接成功
                                                        sharedPreferActivity?.setLoginId(OHInterface.getG_server().login_id.toString())
                                                        MainServer.getG_server().m_local_id = OHInterface.getG_server().login_id
                                                        context?.startActivity(Intent(context, OpenDoor::class.java))
                                                        userviewlogin?.finishs()
                                                        if (OHInterface.getG_server().nickname == "" && OHInterface.getG_server().logo == "") {
                                                          HttpNet.getInstans().obsevice(Observable.create(Observable.OnSubscribe <Login>{ obsetWX->
                                                              HttpNet.getInstans().getOhInter().SyncLogo(OHInterface.getG_server().login_id, userName,headumgur, sex)

                                                          })).subscribe(object :Observer<Login>{
                                                              override fun onCompleted() {

                                                              }

                                                              override fun onError(e: Throwable?) {
                                                              }

                                                              override fun onNext(t: Login?) {

                                                              }

                                                          })
                                                        }
                                                    }else if (t.equals("2")){

                                                         context?.startActivity(Intent(context,Register_Construction_WX::class.java))


                                                    }
                                                    }

                                                }

                                                override fun setError(err: String, boolean: Boolean) {
                                                                if (boolean==false){
                                                                    hint(err)
                                                                }
                                                }

                                            })

                                        } catch (e: JSONException) {
                                            e.printStackTrace()
                                        }
                                    }
                                })
                            }

                        } catch (e: JSONException) {
                            e.printStackTrace()

                        }

                    } else {
                        //登录超时
                    }
                }
            })
        }).start()
    }

}